/**
 * Copyright (C) 2012 The SkyTvOS Project
 * <p/>
 * Version     Date           Author
 * ─────────────────────────────────────
 * 2014年7月15日         Root.Lu
 */

package com.tianci.appstore.framework.db;

import java.io.File;

import android.content.Context;

import com.skyworth.framework.skysdk.android.SkyDBUtil;

public class DB {
    private static final String CONFIG_DB_PATH = "db";
    private String dbFile = null;
    private SkyDBUtil dbUtil = null;
    private Context mContext = null;

    public DB(Context context, String db_file) {
        mContext = context;
        dbFile = getDir(CONFIG_DB_PATH) + "/" + db_file;
        dbUtil = new SkyDBUtil(dbFile);
    }

    private String getDir(String dir) {
        return mContext.getDir(dir, Context.MODE_PRIVATE).getAbsolutePath();
    }

    private boolean isTableExist(DBTable table) {
        synchronized (this) {
            return dbUtil.isTableExist(table.getTableName());
        }
    }

    public final DBTable getTable(Class<?> clazz) {
        synchronized (this) {
            DBTable table = null;
            try {
                table = (DBTable) clazz.newInstance();
                table.setContext(mContext);
                table.setSkyDBUtil(dbUtil);
                table.init();
            } catch (InstantiationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            if (!(new File(dbFile).exists()) || !isTableExist(table))
                dbUtil.createTable(table.getTableName(), table.getColumnsAndTypes());
            return table;
        }
    }
}
